package com.cyj.dream.core.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: 线程池配置
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.core.config
 * @Author: ChenYongJia
 * @CreateTime: 2021-10-11 09:16
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@EnableAsync
@Configuration(proxyBeanMethods = false)
public class ExecutorConfig {

    @Bean(name = "MyThreadPool")
    public Executor MyThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 表示线程池核心线程，正常情况下开启的线程数量。
        executor.setCorePoolSize(40);
        // 配置队列大小
        executor.setQueueCapacity(500);
        // 当核心线程都在跑任务，还有多余的任务会存到此处。
        executor.setMaxPoolSize(50);
        // 非核心线程的超时时长，超长后会被回收。
        executor.setKeepAliveSeconds(60);
        // 配置线程池前缀
        executor.setThreadNamePrefix("MyThreadPool-");
        //用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor exe) -> {
            log.warn("MyThreadPool-当前任务线程池队列已满!");
        });//配置拒绝策略
        executor.initialize();//初始化线程池。
        return executor;
    }

}
